package xyz.spoplar.searchphone.mvp.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import org.json.JSONException;

import java.util.HashMap;
import java.util.Map;

import xyz.spoplar.searchphone.business.HttpUtil;
import xyz.spoplar.searchphone.model.Phone;
import xyz.spoplar.searchphone.mvp.MvpMainView;

/**
 * Created by spoplar on 17-8-15.
 */
public class MainPresenter extends BasePresenter{

    String mUrl = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
    MvpMainView mvpMainView;
    Phone mphone;
    public MainPresenter(MvpMainView mainView){
        mvpMainView = mainView;
    }

    public Phone getPhoneInfo(){
         return mphone;
    }

    public void searchPhoneInfo(String phone){
        if(phone.length() !=11){

            mvpMainView.showToast("请输入正确的手机号");
            return;
        }
        mvpMainView.showLoading();
        //写上http的逻辑
        sendHttp(phone);
    }


    private  void sendHttp(String phone){
        Map<String,String> map = new HashMap<String,String>();
        map.put("tel",phone);


        HttpUtil httpUtil = new HttpUtil(new HttpUtil.HttpResponse() {
            @Override
            public void onSuccess(Object object) {
                String json = object.toString();
                int index = json.indexOf("{");
                json = json.substring(index,json.length());
                //JSON OBJECT
                //mphone=parseModelWithOrgJson(json);
                mphone=parseModelWithGson(json);
                //mphone=parseModelWithFastJson(json);

                mvpMainView.hideLoading();
                mvpMainView.updateView();
            }

            @Override
            public void onFail(String error) {
                mvpMainView.showToast(error);
                mvpMainView.hideLoading();
            }
        });
        httpUtil.sendGetHttp(mUrl,map);
    }

    private Phone parseModelWithOrgJson(String json){
        Phone phone = new Phone();

        try {
            org.json.JSONObject jsonObject = new org.json.JSONObject(json);
            String value = jsonObject.getString("telString");
            phone.setTelString(value);
            value = jsonObject.getString("province");
            phone.setProvince(value);
            value = jsonObject.getString("catName");
            phone.setCatName(value);
            value = jsonObject.getString("carrier");
            phone.setCarrier(value);

            System.out.println(phone);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return phone;
    }

    private Phone parseModelWithGson(String json){
        Gson gson = new Gson();
        Phone phone = gson.fromJson(json,Phone.class);
        return phone;
    }
    private Phone parseModelWithFastJson(String json){
        Phone phone = JSONObject.parseObject(json,Phone.class);
        return phone;
    }
}
